using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using UnityEngine;

/// <summary>
/// 网上数据下载的控制器
/// </summary>
public class DataFetchController : BatchProcessor
{
    
    // Start is called before the first frame update
    void Start()
    {
        
    }
    
    /// <summary>
    /// 请求获取股票列表
    /// </summary>
    [ContextMenu("RequestAllStocks")]
    public async void RequestAllStocks()
    {
        List<StockData> allStocks = await BYAPIDataController.instance.RequestAllStocksData();
        //筛选出主板股
        allStocks = allStocks.AllWhere(e => StockCommonFunctions.CheckIfZhuBan(e.dm) && e.dm !="603205" && e.dm !="000508"
        && e.dm != "000550"&&e.dm != "600550" &&e.dm != "000993"&&e.dm != "603395")
            .AsList();
        
        if (!Directory.Exists(Application.streamingAssetsPath))
        {
            Directory.CreateDirectory(Application.streamingAssetsPath);
        }
        
        string str = Newtonsoft.Json.JsonConvert.SerializeObject(allStocks);
        Debug.Log($"first stock:{Newtonsoft.Json.JsonConvert.SerializeObject(allStocks[0])}");

        File.WriteAllText(StocksDataController.allStocksFilePath, str);
    }
    [ContextMenu("GetAllStocksAllData")]
    public void GetAllStockSubData()
    {
        // m_curReqStockIndex = 0;
        // m_curReqStocks = new List<StockData>( StocksDataController.instance.allStocks);
        // if (fetchStocksCount > 0)
        //     m_curReqStocks = m_curReqStocks.GetRange(0, fetchStocksCount);
        // GetStockSubData();
        
        DoActionToAllStocks(GetStockSubData);
    }

    public void GetStockSubData(StockData stockData)
    {
         GetStockSubData(stockData,true,true);
    }
    /// <summary>
    /// 请求获取所有股票的交易、主力资金、资金流入、成交分布数据
    /// </summary>
    public async void GetStockSubData(StockData stockData, bool skipZijinliuru, bool skipChengjiaofenbu)
    {
        string stock = stockData.dm;

        bool allSkip = true;
        bool allSuc = true;
        string path = StocksDataController.stockTransitionsFilePath(stock);
        if (File.Exists(path))
            Debug.Log($"跳过Transition：{stock}");
        else { bool suc = await DataFetchController.RequestStockTransitions(stock); if (!suc) allSuc = false; allSkip = false; }
        
        path = StocksDataController.stockZhuLiZiJinFilePath(stock);
        if (File.Exists(path))
            Debug.Log($"跳过ZhuLiZiJin：{stock}");
        else {bool suc =  await DataFetchController.RequestStockZhuLiZiJin(stock);if (!suc) allSuc = false; allSkip = false; }

        if (!skipZijinliuru)
        {
            path = StocksDataController.stockZiJinLiuRuFilePath(stock);
            if (File.Exists(path))
                Debug.Log($"跳过ZiJinLiuRu：{stock}");
            else
            {
                bool suc = await DataFetchController.RequestStockZiJinLiuRu(stock);
                if (!suc) allSuc = false;
                allSkip = false;
            }
        }

        path = StocksDataController.stockJieDuanZhuLiFilePath(stock);
        if (File.Exists(path))
            Debug.Log($"跳过JieDuanZhuLi：{stock}");
        else
        {bool suc = await DataFetchController.RequestStockJieDuanZhuLi(stock);;if (!suc) allSuc = false; allSkip = false; }

        if (!skipChengjiaofenbu)
        {
            path = StocksDataController.stockChengJiaoFenBuFilePath(stock);
            if (File.Exists(path))
                Debug.Log($"跳过ChengJiaoFenBu：{stock}");
            else
            {
                bool suc = await DataFetchController.RequestStockChengJiaoFenBu(stock);
                if (!suc) allSuc = false;
                allSkip = false;
            }
        }

        float interval = 14f;
        if (skipZijinliuru) interval -= 3;
        if (skipChengjiaofenbu) interval -= 3;
        
        if (allSkip)
            actionInterval = 0;
        else
            actionInterval = interval;
    }

    #region test
    [ContextMenu("RequestAllTransitions")]
    void RequestAllTransitions()
    {
        DirectoryInfo info = new DirectoryInfo(StocksDataController.stockTransitionsDir);
        m_curReqStockIndex = 0;
        m_curReqStocks = new List<StockData>( StocksDataController.instance.allStocks);
        
        ReqStockDatas(RequestStockTransitions,RequestAllTransitions);
    }
    
    [ContextMenu("ReuestAllZiJinLiuRu")]
    void ReuestAllZiJinLiuRu()
    {  
        DirectoryInfo info = new DirectoryInfo(StocksDataController.stockZiJinLiuRuDir);
        m_curReqStockIndex = 0;
        m_curReqStocks = new List<StockData>(StocksDataController.instance.allStocks);
            
        ReqStockDatas(RequestStockZiJinLiuRu, ReuestAllZiJinLiuRu);
    } 
    [ContextMenu("ReuestAllJieDuanZhuLi")]
    void ReuestAllJieDuanZhuLi()
    {  
        DirectoryInfo info = new DirectoryInfo(StocksDataController.stockJieDuanZhuLiDir);
        m_curReqStockIndex = 0;
        m_curReqStocks = new List<StockData>(StocksDataController.instance.allStocks);
            
        ReqStockDatas(RequestStockJieDuanZhuLi, ReuestAllJieDuanZhuLi);
    }
    [ContextMenu("ReuestAllChengJiaoFenBu")]
    void ReuestAllChengJiaoFenBu()
    {  
        DirectoryInfo info = new DirectoryInfo(StocksDataController.stockChengJiaoFenBuDir);
        m_curReqStockIndex = 0;
        m_curReqStocks = new List<StockData>(StocksDataController.instance.allStocks);
            
        ReqStockDatas(RequestStockChengJiaoFenBu, ReuestAllChengJiaoFenBu);
    }
    
    async void ReqStockDatas(Func<string,Task<bool>> getDataMethod, Action onFail)
    {
        if (m_curReqStockIndex >= m_curReqStocks.Count)
        {
            Debug.Log("结束");
            return;
        }
        string dm = m_curReqStocks[m_curReqStockIndex].dm;
        
        string path = StocksDataController.stockTransitionsFilePath(dm);
        if (File.Exists(path))
        {
            Debug.Log($"跳过：{dm}");
            m_curReqStockIndex++;
            ReqStockDatas(getDataMethod, onFail);
            return;
        }

        bool suc = await getDataMethod(dm);
        if (suc)
        {
            m_curReqStockIndex++;
            DoActionDelay.DelayAction(3f, () => ReqStockDatas(getDataMethod,onFail));
            //Debug.Log($"req {dm} suc, delay to req next");
        }
        else
        {
            Debug.LogError("请求出错，一会重新继续");
            DoActionDelay.DelayAction(5f, onFail);
        }
    }

    static void SaveDataToFile(StockSubData st,string path)
    {
        string str = Newtonsoft.Json.JsonConvert.SerializeObject(st);
        string dir = System.IO.Path.GetDirectoryName(path);
        //Debug.Log($"{path} , dir is:{dir}");
        if (!Directory.Exists(dir))
        {
            Debug.Log($"dir not exist, create:{dir}");
            Directory.CreateDirectory(dir);
        }
        File.WriteAllText(path, str);
    }
    #endregion
    
    #region request
    /// <summary>
    /// 请求获取股票的所有交易
    /// </summary>
    /// <param name="stockCode"></param>
    /// <returns></returns>
    public static async Task<bool> RequestStockTransitions(string stockCode)
    {
        var list = await BYAPIDataController.instance.RequestAllTransitionsData(stockCode);
        if(list == null)
            return false;
            
        StockTranstions st = new StockTranstions();
        st.stockCode = stockCode;
        st.transitionDatas = list;
        
        SaveDataToFile(st, StocksDataController.stockTransitionsFilePath(stockCode));
       
        if(list.Count > 0)
            Debug.Log($"first trans:{Newtonsoft.Json.JsonConvert.SerializeObject(list[0])}");
        return true;
    }
    /// <summary>
    /// 请求获取股票的每分钟主力资金走势
    /// </summary>
    /// <param name="stockCode"></param>
    /// <returns></returns>
    public static async Task<bool> RequestStockZhuLiZiJin(string stockCode)
    {
        var list = await BYAPIDataController.instance.RequestZhuLiZiJinData(stockCode);
        if(list == null)
            return false;
            
        var st = new StockZhuLiZiJin();
        st.stockCode = stockCode;
        st.zhulizijinDatas = list;

        SaveDataToFile(st, StocksDataController.stockZhuLiZiJinFilePath(stockCode));
        if(list.Count > 0)
            Debug.Log($"first Zhulizijin:{Newtonsoft.Json.JsonConvert.SerializeObject(list[0])}");
        return true;
    }
    /// <summary>
    /// 获取资金流入趋势
    /// </summary>
    /// <param name="stockCode"></param>
    /// <returns></returns>
    public static async Task<bool> RequestStockZiJinLiuRu(string stockCode)
    {
        var list = await BYAPIDataController.instance.RequestZiJinLiuRuData(stockCode);
        if(list == null)
            return false;
            
        var st = new StockZiJinLiuRu();
        st.stockCode = stockCode;
        st.ziJinLiuRuDatas = list;
        
        SaveDataToFile(st, StocksDataController.stockZiJinLiuRuFilePath(stockCode));
        
        if(list.Count > 0)
            Debug.Log($"first Zhulizijin:{Newtonsoft.Json.JsonConvert.SerializeObject(list[0])}");
        return true;
    }
    /// <summary>
    /// 获取阶段主力动向
    /// </summary>
    /// <param name="stockCode"></param>
    /// <returns></returns>
    public static async Task<bool> RequestStockJieDuanZhuLi(string stockCode)
    {
        List<JieDuanZhuLiData> list = await BYAPIDataController.instance.RequestJieDuanZhuLiData(stockCode);
        if(list == null)
            return false;
            
        var st = new StockJieDuanZhuLi();
        st.stockCode = stockCode;
        st.jieDuanZhuLiDatas = list;
        
        SaveDataToFile(st, StocksDataController.stockJieDuanZhuLiFilePath(stockCode));
        
        if(list.Count > 0)
            Debug.Log($"first Jieduanzhuli:{Newtonsoft.Json.JsonConvert.SerializeObject(list[0])}");
        return true;
    }
    
    /// <summary>
    /// 获取历史成交分布
    /// </summary>
    /// <param name="stockCode"></param>
    /// <returns></returns>
    public static async Task<bool> RequestStockChengJiaoFenBu(string stockCode)
    {
        List<ChengJiaoFenBuData> list = await BYAPIDataController.instance.RequestChengJiaoFenBuData(stockCode);
        if(list == null)
            return false;
            
        var st = new StockChengJiaoFenBu();
        st.stockCode = stockCode;
        st.chengJiaoFenBuDatas = list;
        
        SaveDataToFile(st, StocksDataController.stockChengJiaoFenBuFilePath(stockCode));
        
        if(list.Count > 0)
            Debug.Log($"first chengjiaofenbu:{Newtonsoft.Json.JsonConvert.SerializeObject(list[0])}");
        return true;
    }
    #endregion
    
    // Update is called once per frame
    void Update()
    {
        
    }

    protected override void onCompleted()
    {
        
    }
}